﻿using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Text;

namespace BabyPoetryConference.Extensions
{
    public static class ConfigurationSectionExtension
    {
        public static string GetString(this IConfigurationSection section, string key)
        {
            var sections = section.GetChildren();
            foreach(var item in sections)
            {
                if (item.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
                {
                    return item.Value;
                }
            }
            throw new KeyNotFoundException($"找不到key={key}对应的配置");
        }

        public static int GetInt(this IConfigurationSection section, string key)
        {
            var sections = section.GetChildren();
            foreach (var item in sections)
            {
                if (item.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
                {
                    return int.Parse(item.Value);
                }
            }
            throw new KeyNotFoundException($"找不到key={key}对应的配置");
        }

        public static bool GetBoolean(this IConfigurationSection section, string key)
        {
            var sections = section.GetChildren();
            foreach (var item in sections)
            {
                if (item.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
                {
                    if(item.Value.Equals("yes", StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                    else if(item.Value.Equals("no", StringComparison.OrdinalIgnoreCase))
                    {
                        return false;
                    }
                    return Boolean.Parse(item.Value);
                }
            }
            throw new KeyNotFoundException($"找不到key={key}对应的配置");
        }
    }
}
